<?php

namespace App\Http\Requests\Admin\V1\SplashAdvert;

use App\Http\Requests\ApiRequest;
use App\Models\Url;
use App\Rules\ImageFile;
use Illuminate\Validation\Rule;

/**
 * Class SplashAdvertDataRequest
 *
 * @property array descriptions
 *
 * @package App\Http\Requests\Admin\V1\SplashAdvert
 */
class SplashAdvertDataRequest extends ApiRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
                'name'                   => 'required|string',
                'advert_type_id'         => 'required|int',
                'play_second'            => 'nullable|int',
                'can_skip'               => 'required|int',
                'sort_order'             => 'required|int',
                'started_at'             => 'required|date',
                'ended_at'               => 'required|date',
                'descriptions.*'         => 'required|array',
                'descriptions.*.content' => [(new ImageFile)->limitSize(200 * 1024)],
            ] + $this->redirectableRules();
    }

    protected function redirectableRules()
    {
        $url_basename = class_basename(Url::class);

        $description_rule = [
            'descriptions.*.redirectable_id' => 'int|min:0',
            'descriptions.*.redirectable_type' => [
                'string', Rule::in([$url_basename,])
            ],
        ];

        foreach ($this->descriptions as $language_id => $description) {
            $desc_locale_url_key = "descriptions.$language_id.redirect_url";

            $description_rule[$desc_locale_url_key] = "required_if:$desc_locale_url_key,$url_basename|url";
        }

        return $description_rule;
    }
}
